package com.wl.myclocksource.controller;

import com.wl.myclocksource.init.PortInit;
import com.wl.myclocksource.lister.MyLister;
import com.wl.myclocksource.utils.SerialPortUtil;
import gnu.io.SerialPort;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: wangwang
 * @Date: 2020/11/18 13:49
 */
@RestController
@RequestMapping("api")
public class PortController {

    @Value("${portname}")
    private String portname;

    private   ResponseEntity responseEntity = null;


    @RequestMapping("start")
    public ResponseEntity start(){
        try {
            SerialPortUtil serialPortUtil = SerialPortUtil.getSerialPortUtil();
            //打开该对应portname名字的串口
            PortInit.serialPort = serialPortUtil.openPort(portname, 9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            //给对应的serialPort添加监听器
            serialPortUtil.addListener(PortInit.serialPort,new MyLister());

            responseEntity = new ResponseEntity("开启成功",HttpStatus.OK);
        }catch (Exception e){
            responseEntity = new ResponseEntity("开启失败",HttpStatus.NO_CONTENT);
        }
        return responseEntity;
    }

    @RequestMapping("stop")
    public ResponseEntity stop(){
        try {
            SerialPortUtil serialPortUtil = SerialPortUtil.getSerialPortUtil();
            serialPortUtil.removeListener(PortInit.serialPort,new MyLister());
            serialPortUtil.closePort(PortInit.serialPort);

            responseEntity = new ResponseEntity("关闭成功",HttpStatus.OK);
        }catch (Exception e){
            responseEntity = new ResponseEntity("关闭失败",HttpStatus.NO_CONTENT);
        }
        return responseEntity;
    }

}
